package com.runshu.newsmartark.reader.base;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.runshu.newsmartark.base.BaseActivity;
import com.runshu.newsmartark.event.BindEventBus;
import com.runshu.newsmartark.event.Event;
import com.runshu.newsmartark.event.EventBusUtils;
import com.runshu.newsmartark.event.EventCode;
import com.runshu.newsmartark.reader.helper.InventoryBuffer;
import com.runshu.newsmartark.reader.helper.ReaderHelper;
import com.runshu.newsmartark.reader.helper.ReaderSetting;

import java.util.ArrayList;
import java.util.List;


/**
 * Demo class
 *
 * @author yu
 * @date 2020/11/9
 * @decs：
 */
public abstract class TakeStockBase extends BaseActivity {
    protected static InventoryBuffer m_curInventoryBuffer;
    public ReaderHelper mReaderHelper;
    public ReaderBase mReader;
    public static ReaderSetting m_curReaderSetting;
    private LocalBroadcastManager lbm;
    public Context context;
    private List<InventoryBuffer.InventoryTagMap> data;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        context = this;
        super.onCreate(savedInstanceState);
        lbm = LocalBroadcastManager.getInstance(this);
        IntentFilter itent = new IntentFilter();
        data = new ArrayList<>();
        itent.addAction(ReaderHelper.BROADCAST_WRITE_LOG);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_INVENTORY_REAL);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_INVENTORY);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_FAST_SWITCH_TERMINAL);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_FAST_SWITCH);
        itent.addAction(ReaderHelper.BROADCAST_WRITE_LOG);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_READER_SETTING);
        lbm.registerReceiver(mRecv, itent);
        try {
            mReaderHelper = ReaderHelper.getDefaultHelper();
            mReader = mReaderHelper.getReader();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        m_curInventoryBuffer = mReaderHelper.getCurInventoryBuffer();
        m_curReaderSetting = mReaderHelper.getCurReaderSetting();
        initFastSwitchParamter();


    }

    private void initFastSwitchParamter() {
        try {
            byte[] antPara = null;
            byte[] session = null;
            byte[] repeats = null;
            antPara = new byte[16];
            antPara[0] = (byte) 0;
            antPara[2] = (byte) 1;
            antPara[4] = (byte) 2;
            antPara[6] = (byte) 3;
            antPara[8] = (byte) 4;
            antPara[10] = (byte) 5;
            antPara[12] = (byte) 6;
            antPara[14] = (byte) 7;

            antPara[1] = (byte) 1;
            antPara[3] = (byte) 1;
            antPara[5] = (byte) 1;
            antPara[7] = (byte) 1;
            antPara[9] = (byte) 1;
            antPara[11] = (byte) 1;
            antPara[13] = (byte) 1;
            antPara[15] = (byte) 1;

//            if (mFastSession.isChecked()) {
            session = new byte[11];

            session[5] = (byte) 1; //设置sessionS1
            session[6] = (byte) 0;//设置session A
            session[0] = Byte.parseByte("0");  //设置recervers
            session[1] = Byte.parseByte("0");
            session[2] = Byte.parseByte("0");
            session[3] = Byte.parseByte("0");
            session[4] = Byte.parseByte("0");

            session[7] = Byte.parseByte("0");//优化
            session[8] = Byte.parseByte("0");//连续
            session[9] = Byte.parseByte("0");//标签数量
//                if (mFastPhase.isChecked()) {
//                    session[10] = 0x01;  //phase
//                }
//            }


            byte[] param = null;
            param = new byte[antPara.length + session.length + 2];
            System.arraycopy(antPara, 0, param, 0, antPara.length);
            param[antPara.length] = Byte.parseByte("0");
            System.arraycopy(session, 0, param, antPara.length + 1, session.length);
            param[param.length - 1] = Byte.parseByte("1");


            m_curInventoryBuffer.nFastSwitchAntsParams = param;
            //运行次数
            int runTimes = Integer.parseInt("2");
            if (runTimes == 0) {
                throw new Exception();
            }
            m_curInventoryBuffer.nRunTimes = runTimes;
            //时间间隔
            m_curInventoryBuffer.nTimeInterval = Integer.parseInt("0");
        } catch (Exception e) {
            Toast.makeText(context, "Invaild parameter Exception!", Toast.LENGTH_SHORT).show();
        }

    }

    private boolean bTmpInventoryFlag = true;

    public void startstop(boolean start) {
        Log.e("serport", "startscan");
        bTmpInventoryFlag = false;
        m_curInventoryBuffer.btRepeat = 0x00;
        m_curInventoryBuffer.nIndexAntenna = 0;
        m_curInventoryBuffer.nCommond = 0;
        m_curInventoryBuffer.bLoopInventoryReal = false;
        m_curInventoryBuffer.bLoopInventoryReal = true;
        m_curInventoryBuffer.btRepeat = 0;
        //每条存盘的次数
        String strRepeat = "1";

        m_curInventoryBuffer.btRepeat = (byte) Integer.parseInt(strRepeat);

        //高级设置
        m_curInventoryBuffer.bLoopInventoryReal = false;
        m_curInventoryBuffer.bLoopInventory = true;
        m_curInventoryBuffer.bLoopCustomizedSession = false;
        initFastSwitchParamter();
        if (!start) {
            mReaderHelper.setInventoryFlag(false);
            m_curInventoryBuffer.bLoopInventoryReal = false;
            m_curInventoryBuffer.bLoopInventory = false;
            m_curInventoryBuffer.bLoopCustomizedSession = false;
            m_curInventoryBuffer.clearInventoryResult();
            return;
        } else {
            mReaderHelper.runLoopFastSwitch();
        }

    }


    public void onOpenDoor() {

    }


    public void onCloseDoor() {
        closeLigth();
        startstop(true);
    }

    public void closeLigth() {
        //关灯
        mReader.writeGpioValue(m_curReaderSetting.btReadId, (byte) 0x04, (byte) 0x00);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
            }
        }, 100);
    }


    public void opeanDoor() {
        //关门
        getWindow().getDecorView().postDelayed(new Runnable() {
            @Override
            public void run() {
                mReader.writeGpioValue(m_curReaderSetting.btReadId, (byte) 0x03, (byte) 0x00);
            }
        }, 4000);
    }


    public static String bytesToHexString(byte src) {
        StringBuilder stringBuilder = new StringBuilder("");

        int v = src & 0xFF;
        String hv = Integer.toHexString(v);
        if (hv.length() < 2) {
            stringBuilder.append(0);
        }
        stringBuilder.append(hv);

        return stringBuilder.toString();
    }

    // add by lei.li 2016/11/14
    private final BroadcastReceiver mRecv = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_READER_SETTING)) {
                byte btCmd = intent.getByteExtra("cmd", (byte) 0x00);

                if (btCmd == CMD.READ_GPIO_VALUE || btCmd == CMD.WRITE_GPIO_VALUE) {
                    if (m_curReaderSetting.btGpio1Value == 0x00) {
                        onCloseDoor();
                        EventBusUtils.sendEvent(new Event(EventCode.EventClose));
                        Log.e( "hh","g1"+m_curReaderSetting.btGpio1Value+"g2"+m_curReaderSetting.btGpio2Value+"close"+System.currentTimeMillis() );
                    } else {
                        onOpenDoor();
                        Log.e( "hh","g1"+m_curReaderSetting.btGpio1Value+"g2"+m_curReaderSetting.btGpio2Value+"open" +System.currentTimeMillis());
                    }
                }

            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_WRITE_LOG)) {


            }

            if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_INVENTORY_REAL)
                    || intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_INVENTORY)
                    || intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_FAST_SWITCH)) {
                Log.d("Real time receive", Thread.currentThread().getName());
                byte btCmd = intent.getByteExtra("cmd", (byte) 0x00);
                Log.d("action", bytesToHexString(btCmd));
                switch (btCmd) {
                    case CMD.REAL_TIME_INVENTORY:
                    case CMD.CUSTOMIZED_SESSION_TARGET_INVENTORY:
                        if (m_curInventoryBuffer.lsTagList.size() > 0) ;
                    {

                        Log.d("TAGS", m_curInventoryBuffer.lsTagList.get(0).strEPC);
                    }


                    mHandler.removeCallbacks(mRefreshRunnable);
                    mHandler.postDelayed(mRefreshRunnable, 2000);
                    // add by lei.li 2016/11/14
                    mLoopHandler.removeCallbacks(mLoopRunnable);
                    mLoopHandler.postDelayed(mLoopRunnable, 2000);
                    //refreshText();
                    break;
                    case CMD.GET_INVENTORY_BUFFER:
                    case CMD.GET_AND_RESET_INVENTORY_BUFFER:
                        break;
                    case ReaderHelper.INVENTORY_ERR:
                    case ReaderHelper.INVENTORY_ERR_END:
                    case ReaderHelper.INVENTORY_END:
                        // add by lei.li have some problem why it was annotation
                        // refreshList();
                        // add by lei.li
                        // add by lei.li 2016/11/
                        if (mReaderHelper.getInventoryFlag() /* || bTmpInventoryFlag */) {
                            mLoopHandler.removeCallbacks(mLoopRunnable);
                            mLoopHandler.postDelayed(mLoopRunnable, 2000);

                        } else {
                            mLoopHandler.removeCallbacks(mLoopRunnable);
                            // add by lei.li 2016/11/14
                            mHandler.removeCallbacks(mRefreshRunnable);
                            // add by lei.li 2016/11/14
                        }

                        // start_add by lei.li 2016/11/04
                        // refreshStartStop(false);
                        // end_add by lei.li 2016/11/04
                        // start_add by lei.li 2016/11/04
                        break;
                }

            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_WRITE_LOG)) {
            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_FAST_SWITCH_TERMINAL)) {
                data.clear();
                data.addAll(m_curInventoryBuffer.lsTagList);
                onScanResult(data);
                Log.d("action", "停止");
            }
        }
    };

    protected void onScanResult(List<InventoryBuffer.InventoryTagMap> lsTagList) {
        startstop(false);
    }

    ;


    private Handler mHandler = new Handler();
    private Runnable mRefreshRunnable = new Runnable() {
        public void run() {
            //refreshList();
            mHandler.postDelayed(this, 2000);
        }
    };
    private Handler mLoopHandler = new Handler();
    private Runnable mLoopRunnable = new Runnable() {
        public void run() {
            /*
             * byte btWorkAntenna =
             * m_curInventoryBuffer.lAntenna.get(m_curInventoryBuffer
             * .nIndexAntenna); if (btWorkAntenna < 0) btWorkAntenna = 0;
             * mReader.setWorkAntenna(m_curReaderSetting.btReadId,
             * btWorkAntenna);
             */
            mReaderHelper.runLoopInventroy();
            mLoopHandler.postDelayed(this, 2000);
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (lbm != null)
            lbm.unregisterReceiver(mRecv);
    }
}